package com.skycong.hello77;

/**
 * 模拟ArrayList
 * Created by Kiki on 2018/6/20.
 */

public class JavaOwnList {
    public int size;
    private int length;
    private Object[] elements;

    public JavaOwnList() {
        this(16);
    }

    public JavaOwnList(int capacity) {
        elements = new Object[capacity];
        length = capacity;
    }

    //向一个list里面对象
    public boolean add(Object o) {
        if (size >= length) {
            //数据是固定的，所以要扩容
            capacity();
        }
        elements[size++] = o;
        return true;
    }

    //扩容方法
    private void capacity() {
        //新建一个数组，当size>length时，动态的进行扩容
        Object[] t = new Object[length * 2];
        for (int i = 0; i < length; i++) {
            t[i] = elements[i];
        }
        length = length * 2;
        elements = t;
    }

    //传入索引，移除相对应索引的值
    public Object remove(int index) {
        if (index < 0 || index > size) {
            System.out.println("数据下标越界了");
        }
        Object element = elements[index];
        for (int i = index; i < size; i++) {
            elements[i] = elements[i + 1];
        }
        size--;
        return element;
    }

    //重写toString()方法，用StringBuffer
    @Override
    public String toString() {
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < size; i++) {
            buffer.append(elements[i]).append(",");
        }
        return "list:{" + buffer + "}";
    }

    public static void main(String[] args) {
        JavaOwnList list = new JavaOwnList();
        for (int i = 0; i < 37; i++) {
            list.add("aassaa" + i);
        }
        System.out.println(list.remove(1));
        System.out.println(list.remove(1));
        System.out.println(list.remove(1));
        System.out.println(list);
    }
}
